package com.leimo.java_socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

/**
 * socket服务
 *
 * @author 段誉
 * @create 2019-02-26 11:29
 */
public class MySocketServer extends Thread {
  private ServerSocket serverSocket;

  public MySocketServer(int port) throws IOException {
    serverSocket = new ServerSocket(port);
    serverSocket.setSoTimeout(10000);
  }

  @Override
  public void run() {
    while(true)
    {
      try
      {
        System.out.println("等待远程连接，端口号为：" + serverSocket.getLocalPort() + "...");
        Socket server = serverSocket.accept();
        System.out.println("远程主机地址：" + server.getRemoteSocketAddress());
        DataInputStream in = new DataInputStream(server.getInputStream());
        System.out.println(in.readUTF());
        DataOutputStream out = new DataOutputStream(server.getOutputStream());
        out.writeUTF("谢谢连接我：" + server.getLocalSocketAddress() + "\nGoodbye!");
        server.close();
      }catch(SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      }catch(IOException e) {
        e.printStackTrace();
        break;
      } catch (Exception e) {
        e.printStackTrace();
        break;
      }
    }
  }

  public static void main(String [] args) {
    try
    {
      Thread t = new MySocketServer(9998);
      t.run();
    }catch(IOException e)
    {
      e.printStackTrace();
    }
  }
}
